
<div class="row">
    <div class="container-fluid">
        <div class="col-lg-12 no-padding">
            <section class="content-header">
                <ol class="breadcrumb">
                    <li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li>
                    <li><a href="#" class="active">文件浏览</a></li>
                </ol>
            </section>
            <!-- Main content -->
            <section class="content">
                <div class="row">
                    <div class="col-lg-2 no-padding" id="myLeft">
                            <div class="jax-box">
                                <div style="overflow: scroll">
                                <div class="checkbox" style="border-bottom: 1px solid #666;padding:0px 0px 10px 10px">
                                        <label>
                                            <input type="checkbox" id="dg_select" checked>
                                            （递归查询）
                                        </label>

                                        <a  class="btn btn-link pull-right" style="padding: 0px;color: #666" id="btn_kuoda">
                                            <i class="fa fa-fw fa-angle-double-right"></i>
                                        </a>
                                </div>
                                    <ul id="treeDemo" class="ztree"></ul>
                                </div>
                            </div>

                    </div>
                    <div class="col-lg-10 no-padding" id="myRight">
                        <div class="jax-box">
                            <form class="form-inline">
                               <!-- <div class="form-group">
                                    <label for="fileNumber" style="font-weight: bold;color:#0d6aad">文件ID:</label>
                                    <input type="text" class="form-control" id="fileNumber" name="fileNumber" placeholder="ID精确查找" style="border-color:#00a2d4;width: 100px">
                                </div>-->
                                <div class="form-group">
                                    <label for="fileInfoName">文件名:</label>
                                    <input type="text" class="form-control" id="fileInfoName" name="fileInfoName" placeholder="模糊条件" style="width: 150px">
                                </div>
                                <div class="form-group">
                                    <label for="creatorName">提供者:</label>
                                    <input type="text" class="form-control" id="creatorName" name="creatorName" placeholder="模糊条件" style="width: 100px">
                                </div>
                                <div class="form-group">
                                    <label for="fileKeys">关键说明:</label>
                                    <input type="text" class="form-control" id="fileKeys" name="fileKeys" placeholder="模糊条件" style="width: 100px">
                                </div>
                                <a id="btn_query" class="btn btn-info" >查询</a>
                                <input type="hidden" name="categoryId" id="categoryId">
                                <input type="hidden" name="categoryName" id="categoryName">
                            </form>
                        </div>
                        <div class="jax-box jax-box-table">
                            <div style="overflow: scroll">
                            <div id="toolbar">
                                <div class="btn-group">
                                    <shiro:hasPermission name="fileUpload">
                                    <a id="btn_upload" class="btn btn-info">
                                        <i class="fa fa-upload"></i>
                                        文件上传
                                    </a>
                                    </shiro:hasPermission>

                                    <shiro:hasPermission name="download:applicant">
                                        <a id="btn_batch_download" class="btn btn-warning">
                                            <i class="fa fa-download"></i>
                                            批量申请
                                        </a>
                                    </shiro:hasPermission>

                                    <shiro:hasPermission name="download:immediately">
                                    <a id="btn_batch_download_immediately" class="btn btn-success">
                                        <i class="fa fa-download"></i>
                                        批量下载
                                    </a>
                                    </shiro:hasPermission>
                                </div>
                            </div>

                            <table id="table" class="table table-striped" style="min-width: 1200px"> </table>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 文件详情模态框 -->
            <div id="fileInDetailfoModal" class="modal fade " tabindex="-1" role="dialog">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-body">
                            <div class="box box-widget">
                                <div class="box-header with-border">


                                    <div>
                                       <!-- <h5 id="fileInfoId">ID: 34343 </h5>-->
                                        <h3 class="pull-left">
                                            <span id="fileName4Details">java web开发课程大纲.zip</span>&nbsp;&nbsp;
                                        </h3>
                                    </div>

                                    <!-- /.user-block -->
                                    <div class="box-tools">
                                        <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
                                        </button>
                                        <button type="button" class="btn btn-box-tool" data-dismiss="modal" aria-label="Close"><i class="fa fa-times"></i></button>
                                    </div>
                                    <!-- /.box-tools -->
                                </div>


                                <!-- /.box-header -->
                                <div class="box-body">
                                    <div class="attachment-block clearfix">
                                        <dl>
                                            <dt>关键说明:</dt>
                                            <dd>&nbsp;&nbsp;&nbsp;&nbsp;<span id="fileKeys4Details"></span></dd>
                                            <dt>类别:</dt>
                                            <dd>&nbsp;&nbsp;&nbsp;&nbsp;<span id="categoryName4Details"></span></dd>
                                            <dt>提供者:</dt>
                                            <dd>&nbsp;&nbsp;&nbsp;&nbsp;<span id="creatorName4Details"></span></dd>
                                        </dl>
                                    </div>

                                        <dl>
                                            <dd>
                                                <p id="detail4Details">
                                                </p>
                                            </dd>
                                        </dl>
                                    <!-- Social sharing buttons -->
                                </div>
                                <!-- /.box-body -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            <!-- 编辑文件 模态框 -->
            <div id="fileInfoUpdateModal" class="modal fade" tabindex="-2" role="dialog">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">编辑文件</h4>
                        </div>
                        <div class="modal-body">
                            <div id="formDiv">
                            </div>
                        </div>
                    </div><!-- /.modal-content -->
                </div><!-- /.modal-dialog -->
            </div>
            <div id="categoryLayer" style="display: none;padding-left: 20px;">
                <ul id="categoryTree" class="ztree"></ul>
            </div>

        </div>
    </div>
</div>
<script>
    /* * *权限标识 */
    var downloadApplicantFlag = "[[${@perms.hasPerm('download:applicant')}]]";//申请下载
    var downloadImmediatelyFlag = "[[${@perms.hasPerm('download:immediately')}]]";//申请下载
    var fileInfoEdit = "[[${@perms.hasPerm('fileinfo:edit')}]]";//编辑文件
    var fileInfoDelete = "[[${@perms.hasPerm('fileinfo:delete')}]]";//编辑文件
    var editCategoryFlag = "[[${@perms.hasPerm('category:edit')}]]";
    var deleteCategoryFlag = "[[${@perms.hasPerm('category:delete')}]]";

    /* 类别tree 加载 Start */
    $(function () {
        let treeSetting = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: ""
                }
            },
            edit:{
                enable: (editCategoryFlag=="true"),
                showRemoveBtn: false,//(deleteCategoryFlag=="true"),
                showRenameBtn: (editCategoryFlag=="true"),
                isCopy:false,
                isMove:true,//(editCategoryFlag=="true"),
                prev:true,
                inner:true,
                next:true
            }
            ,
            view:{
                showLine:false,
                selectedMulti:false,
               // fontCss : {color:"red"}
            },
            callback: {
                onClick: function (event, treeId, treeNode, clickFlag) {
                    $("#categoryId").val(treeNode['id']);
                    $("#categoryName").val(treeNode['name']);
                    $("#fileNumber").val('');//清空文件的ID号。
                    $("#btn_query").trigger("click");
                },
                beforeRemove:function (treeId, treeNode) {
                    Core.confirm("确认删除:"+treeNode["name"]+"?",function () {
                        Core.postAjax('/category/delete',{"id":treeNode["id"]},function (data) {
                            if(data.status==200){
                                $.fn.zTree.getZTreeObj(treeId).removeNode(treeNode);
                                layer.msg("删除成功",{time:700});
                            }else {
                                layer.msg(data.msg);
                            }
                        });
                    })
                    return false;
                },
                beforeRename:function(treeId, treeNode, newName, isCancel){
                    if(!isCancel){
                        treeNode.oldName = treeNode.name.trim();
                    }
                },
                onRename:function (event, treeId, treeNode, isCancel) {
                        if(!isCancel){
                            if(treeNode['name'].trim()!==treeNode["oldName"]){
                                let obj = {"id":treeNode['id'],"name":treeNode['name']};
                                Core.postAjax("/category/edit",obj,function (data) {
                                    if(data.status==200){
                                        layer.msg("类别更改成功",{time:700});
                                    }
                                });
                            }
                        }
                },
                onDrop:function (event, treeId, treeNodes, targetNode, moveType) {
                    if(moveType){
                        let obj = {"id":treeNodes[0]['id']};
                        if(moveType==="inner"){
                            obj["parentId"]=targetNode['id'];
                            obj["orderNum"]=0;
                        }else if(moveType=="prev"){
                            obj["parentId"]=targetNode['parentId'];
                            obj["orderNum"]=targetNode['orderNum']-1;
                        }else if(moveType=="next"){
                            obj["parentId"]=targetNode['parentId'];
                            obj["orderNum"]=targetNode['orderNum']+1;
                        }
                        Core.postAjax("/category/edit",obj,function (data) {
                            if(data.status==200){
                                layer.msg("类别更改成功",{time:700});
                            }
                        });
                    }
                }
            }
        };
        Core.postAjax('/category/list',null,function (data) {
           $.fn.zTree.init($("#treeDemo"), treeSetting, data).expandAll(true);
        });
    });
    /* 类别tree 加载 End */

    /* // 查询、表格 Start*/
    $(function () {
        /* 确定提交更改的事件*/
        $("#fileInfoUpdateModal").on("click","#save_EditFileInfo",function () {
            $.ajax({
                url : "fileInfo/edit_submit",
                type : 'POST',
                cache : false,
                data : new FormData($('#editForm')[0]),
                processData : false,
                contentType : false,
                success : function(data) {
                    if(data["status"]==200){
                        $("#fileInfoUpdateModal").modal("hide");
                        Core.refreshTable("#table");
                    }
                    layer.msg("操作成功");
                }
            });
        });


        window.operateEvents  = {
            'click .show_detail': function (e, value, row, index) {
                $("#fileName4Details").html(row.fileName);
                $("#fileKeys4Details").html(row.fileKeys);
                $("#categoryName4Details").html(row.categoryName);
                $("#creatorName4Details").html(row.creatorName);
                $("#detail4Details").html((row.detail||"无详细说明"));
                $("#fileInfoId").html("ID: "+row.fileNumber);
                $("#fileInDetailfoModal").modal("show");
             },
            // 更改操作的方法
            'click .btn_edit': function (e, value, row, index) {
                let id = row.id;
                Core.postAjax("/fileInfo/edit",{id:id},function (data) {
                    $("#formDiv").html(data);
                    $('#detail_edit').wysihtml5({
                        toolbar: {
                            "font-styles": true,// Font styling,e.g. h1,h2,etc.
                            "emphasis": true,// Italics,bold,etc.
                            "lists": true,// (Un)ordered lists,e.g. Bullets,Numbers.
                            "html": true,// Button which allows you to edit the generated HTML.
                            "link": false,// Button to insert a link.
                            "image": false,// Button to insert an image.
                            "color": false,// Button to change color of font
                            "blockquote": true,// Blockquote
                            "size": "sm" // options are xs,sm,lg
                        }
                    } );
                    $("#fileInfoUpdateModal").modal("show");
                },"get");
            },
            //删除 单行/
            'click .btn_del': function (e, value, row, index) {
                let id = row.id;
                Core.confirm("请确认删除：【"+row.fileName+"】",function () {
                   Core.postAjax("/fileInfo/delete",JSON.stringify({"id":id}),function (data) {
                        if(data["data"]){
                            layer.msg("操作成功");
                            Core.refreshTable("#table");
                        }else {
                            layer.msg("删除失败")
                        }
                   },"delete","application/json");
                })
            },

            //申请 下载单行/
           'click .btn_downloadOne': function (e, value, row, index) {
               let id = row.id;
               layer.prompt({
                   formType: 2,
                   value: row.fileName,
                   title: '请输入留言信息（可选）',
                   area: ['250px', '100px'] //自定义文本域宽高
               }, function(val, index, elem){
                   layer.close(index);
                   Core.postAjax("/download/apply/",JSON.stringify({
                       "applicationRemark":val.trim(),
                       "ids":[id]
                   }),function (data) {
                       if(data["data"]){
                           layer.msg("申请成功，在\"我的下载\"中查看审核结果");
                       }else {
                           layer.msg("申请失败")
                       }
                   },"post","application/json");
               });
            },

            //直接下载单行
            'click .btn_downloadOne_immediately': function (e, value, row, index) {
                let id = row.id;
                Core.confirm('下载:'+row.fileName,function () {
                    let ids =[id];
                    layer.msg("正在处理文件",{time:1000},function () {
                        Core.postAjax("/download/immediately",JSON.stringify(ids),function (data) {
                            Core.refreshTable("#table");
                            if(data["data"]){
                                $("<form></form>").attr("action", "/download/"+data["data"]).attr("method", "post")
                                    // .append($("<input>").attr("type", "hidden").attr("name", "path").attr("value", data["data"]))
                                    .appendTo('body').submit().remove();
                            }else {
                                layer.msg("操作失败,服务器异常");
                            }
                        },"post","application/json");
                    })
                });
            }

        };




        var columns = [
            {
                field: 'state',
                checkbox: true,
                valign: 'middle'
            },
            {
                field: 'fileName',
                title: '文件名',
                formatter:function (value, row, index) {
                    var icon = "<i class='fa "+row.fileIcon+"' style='font-size: 20px;'></i>&nbsp;&nbsp;";
                    return icon+' <a href="javascript:void(0)" class="show_detail" ' +
                        '">'+value+'</a>';
                  /*  if(value.length>20){
                        return icon+ ' <a href="javascript:void(0)" class="show_detail" ' +
                            'data-toggle="tooltip" data-placement="top" title="' +value+
                            '">'+(value.substring(0, 12)+"......"+value.substring(value.length-6))+'</a>';
                    }else{
                        return icon+' <a href="javascript:void(0)" class="show_detail" ' +
                            '">'+value+'</a>';
                    }*/
                },
              //  width: 380,
                events: window.operateEvents
            } ,
            {
                field: 'fileKeys',
                title: '关键说明',
                formatter:function (value, row, index) {
                    if(value==null){
                        return "";
                    }
                    // return value;
                    if(value && value.length>40){
                        return ' <span href="javascript:void(0)" class="show_detail" ' +
                            'data-toggle="tooltip" data-placement="top" title="' +value+
                            '">'+(value.substring(0,32)+"......"+value.substring(value.length-6))+'</span>';
                    }else{
                        return ' <span href="javascript:void(0)" class="show_detail" ' +
                            '">'+value+'</span>';
                    }
                },
                width: 300,

            },

            {
                title: '类别',
                formatter:function (value, row, index) {
                    return   "<span style='color: " +(row.categoryId?"#000":"red")+
                        "'>"+row.categoryName+ "</span>";//
                },

            },
            {
                title: '上传者',
                align: 'center',
                formatter:function (value, row, index) {
                    return row.creatorName+"/"+row.createtime;
                }
            },
            {
                title: '操作',
                align: 'center',
                formatter:function (value, row, index) {
                    var download =(downloadApplicantFlag=="true"?'<a  class="table-btn table-btn-warning btn_downloadOne" href="javascript:void(0)"><i class="fa fa-fw fa-download"></i>申请</a> ':"");
                    var downloadImmediately = (downloadImmediatelyFlag=="true"?'<a  class="table-btn table-btn-success btn_downloadOne_immediately" href="javascript:void(0)"><i class="fa fa-fw fa-download"></i>下载</a> ':"");
                    var edit = (fileInfoEdit=="true"?'<a class="table-btn table-btn-info btn_edit" href="javascript:void(0)">编辑</a> ':"");
                    var del = (fileInfoDelete=="true"?'<a  class="table-btn table-btn-danger btn_del" href="javascript:void(0)">删除</a> ':"");
                    return download + downloadImmediately+edit +del;
                },
                events:window.operateEvents,
                //width: 220,
            }


        ]

        let options={
            id:"#table",
            url: '/fileInfo/list',
            method:'get',
            columns:columns,
            toolbar: '#toolbar',
            showRefresh: true,
            pageList: "[10, 25, 50, 100, all]",
            search: true,
            queryParams : queryParams,
            showColumns: false,
            clickToSelect: false,
            fixedColumns: true,
            fixedNumber: 2,
            fixedRightNumber: 0
        }
        Core.initTable(options);

        /*查询参数*/
        function queryParams(params) {
            var temp = {
                limit : params.limit, //页面大小
                pageNo : (params.offset/params.limit)+1, //页码
                fileName : $("#fileInfoName").val(),
                creatorName: $("#creatorName").val(),
                categoryId: $("#categoryId").val(),
                fileKeys: $("#fileKeys").val(),
                fileNumber:$("#fileNumber").val(),
                diGui:(function () {
                    return $("#dg_select").prop('checked')?1:0;
                })()
            };
            return temp;
        }
        //递归查询复选框
        $("#dg_select").change(function () {
            $("#fileNumber").val("");
            $("#btn_query").trigger("click");
        });

        /*查询*/
        $("#btn_query").click(function(){
            Core.refreshTable("#table");
            layer.msg($("#categoryName").val().trim()||"全部类别",{time:500});
        });

        /*批量申请下载*/
        $("#btn_batch_download").click(function(){
            var checkedRows= Core.selectMutiData("#table");
            if(checkedRows){
                layer.prompt({
                    formType: 2,
                    value: ' ',
                    title: '文件数'+checkedRows.length+'，请输入留言信息（可选）',
                    area: ['250px', '100px'] //自定义文本域宽高
                }, function(val, index, elem){
                    layer.close(index);
                    let ids =[];
                    $.each(checkedRows, function (i, item) {
                        ids.push(item.id);
                    });
                    Core.postAjax("/download/apply/",JSON.stringify({
                        "applicationRemark":val.trim(),
                        "ids":ids
                    }),function (data) {
                        if(data["data"]){
                            Core.refreshTable("#table");
                            layer.msg("申请成功，请在\"我的下载\"中查看审核结果");
                        }else {
                            layer.msg("申请失败");
                        }
                    },"post","application/json");
                });

            }
        });

        /*批量直接下载*/
        $("#btn_batch_download_immediately").click(function(){
            var checkedRows= Core.selectMutiData("#table");
            if(checkedRows){
                Core.confirm('下载文件数量:'+checkedRows.length,function () {
                    let ids =[];
                    $.each(checkedRows, function (i, item) {
                        ids.push(item.id);
                    });
                    layer.msg("正在处理文件",{time:1000},function () {
                        Core.postAjax("/download/immediately",JSON.stringify(ids),function (data) {
                            Core.refreshTable("#table");
                            if(data["data"]){
                                $("<form></form>").attr("action", "/download/"+data["data"]).attr("method", "post")
                                    // .append($("<input>").attr("type", "hidden").attr("name", "path").attr("value", data["data"]))
                                    .appendTo('body').submit().remove();
                            }else {
                                layer.msg("服务器异常");
                            }
                        },"post","application/json");
                    })
                });
            }
        });



    });
    /* // 查询、表格 End */
    $(function () {
        /*文件上传弹出框*/
        $("#btn_upload").click(function(){
            let categoryName= $("#categoryName").val();
            if(!categoryName){
                layer.alert('请选择文件类别', {icon: 2});
                return;
            }
            Core.confirm("请确认文件类别：【"+$("#categoryName").val()+"】",function () {
                layer.open({
                    type: 2,
                    content: '/fileInfo/layer/upload',
                    area: ['800px', '600px'],
                    cancel:function () {
                        Core.refreshTable("#table");
                    }
                });
            })
        });
    });



    /*选择类别的树*/
    function showCategorys(flag){
        var ztree;
        //树-初始化设置
        var treeSetting = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId"
                }
            }
        };
        Core.postAjax('/category/list',null,function (data) {
            var topCategorys = {
                name:"顶层分类",
                id:null,
                parentId:null,
                type:0
            }
            data.unshift(topCategorys);
            $.each(data,function (i, item) {
                item.open=true;
            })
            ztree=$.fn.zTree.init($("#categoryTree"), treeSetting, data);
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择分类",
                area: ['300px', '450px'],
                /* shade: 0,
                 shadeClose: false,*/
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    if(node.length==0){
                        layer.msg("请选择一个类别！",function(){});
                        return;
                    }
                    if(flag==1){
                        //选择上级
                        $("#categoryId_edit").val(node[0].id);
                        $("#categoryName_edit").val(node[0].name);
                    }
                    layer.close(index);
                }
            });
        });
    }


    $(function () {
        $("#btn_kuoda").click(function () {
            $("#myLeft").toggleClass("col-lg-2").toggleClass("col-lg-3");
            $("#myRight").toggleClass("col-lg-10").toggleClass("col-lg-9");
            $(this).find("i").toggleClass("fa-angle-double-right").toggleClass("fa-angle-double-left");
        });
    })

</script>
